package com.ds.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ds.command.Command;
import com.ds.command.CommandReportStatus;
import com.ds.common.JDSException;
import com.ds.config.ResultModel;
import com.ds.context.JDSActionContext;
import com.ds.context.WebErrorResultModel;
import com.ds.enums.db.MethodChinaName;
import com.ds.esb.util.EsbFactory;
import com.ds.iot.GWClientService;
import com.ds.iot.client.CommandWebService;
import com.ds.iot.client.DataWebService;
import com.ds.iot.client.GWAccountWebService;
import com.ds.iot.client.GatewayWebService;
import com.ds.iot.json.NetworkInfo;
import com.ds.iot.json.device.*;
import com.ds.server.comet.AbstractCometHandle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/Gateway/api")
public class GWWebAPI implements GWClientService {
    private static final Logger logger = LoggerFactory.getLogger(GWWebAPI.class);

    @MethodChinaName(cname = "网关注册", returnStr = "Register($Gateway)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/Register" })
    @ResponseBody
    public ResultModel<GatewayRegister> register(@RequestBody Gateway gateway) {
	logger.info("注册网关参数:{}", JSON.toJSONString(gateway));
	ResultModel<GatewayRegister> resultModel = new ResultModel<GatewayRegister>();

	Gateway gatway = null;
	try {
	    gatway = getGWAccountWebService().register(gateway).get();
	    resultModel.setData(new GatewayRegister(gatway));

	} catch (Exception e) {
	    logger.error("register:注册网关出错,Gateway:" + JSON.toJSONString(gateway), e);
	    resultModel = new WebErrorResultModel();
	    ((WebErrorResultModel) resultModel).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
	    ((WebErrorResultModel) resultModel).setErrdes(e.getMessage());
	}
	return resultModel;
    }

    @MethodChinaName(cname = "网关激活", returnStr = "Activate($Gateway)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/Activate" })
    @ResponseBody
    public ResultModel<GatewayActivate> activate(@RequestBody Gateway gateway) {
	logger.info("激活网关参数:{}", JSON.toJSONString(gateway));
	ResultModel<GatewayActivate> resultModel = new ResultModel<GatewayActivate>();
	Gateway gatway = null;
	try {

	    gatway = getGWAccountWebService().activate(gateway).get();
	    resultModel.setData(new GatewayActivate(gatway));
	} catch (Exception e) {
	    logger.error("activate:激活网关出错,Gateway:" + JSON.toJSONString(gateway), e);
	    resultModel = new WebErrorResultModel();
	    ((WebErrorResultModel) resultModel).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
	    ((WebErrorResultModel) resultModel).setErrdes(e.getMessage());
	}
	return resultModel;
    }

    @MethodChinaName(cname = "告警报告", returnStr = "AlarmReport($SensorData)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/AlarmReport" })
    @ResponseBody
    public ResultModel alarmReport(@RequestBody SensorData sensordata) {
		logger.info("Method alarmReport data:"+JSONObject.toJSONString(sensordata));

	getDataWebService().addAlarm(sensordata).execute();

	return new ResultModel();
    }

    @MethodChinaName(cname = "绑定状态报告", returnStr = "BindingStatusReport($CommandReportStatus)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/BindingStatusReport" })
    @ResponseBody
    public ResultModel<Boolean> bindingStatusReport(@RequestBody CommandReportStatus report) {

	getCommandWebService().bindingStatusReport(report).execute();
	return new ResultModel();
    }

    @MethodChinaName(cname = "绑定列表报告", returnStr = "BindListReport($BindInfo)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/BindListReport" })
    @ResponseBody
    public ResultModel<Boolean> bindListReport(BindInfo bindInfo) {
	// HttpServletRequest request= ((ServletRequestAttributes)
	// RequestContextHolder.getRequestAttributes()).getRequest();
	// BufferedReader br;
	// try {
	// br = new BufferedReader(new InputStreamReader(request.getInputStream(),"utf-8"));
	// String line = null;
	// StringBuilder sb = new StringBuilder();
	// while ((line = br.readLine()) != null) {
	// sb.append(line);
	// }
	// String json=sb.toString();
	// logger.info("paramsJson="+sb.toString());
	// bindInfo= JSONObject.parseObject(json, BindInfo.class);
	//
	// getCommandWebService().bindListReport(bindInfo).execute();
	//
	// } catch (IOException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }

	return new ResultModel();
    }

    @MethodChinaName(cname = "修改WIFI网络配置", returnStr = "ChangeNetworkResponse($NetworkInfo)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/ChangeNetworkResponse" })
    @ResponseBody
    public ResultModel<NetworkInfo> changeNetworkResponse(@RequestBody NetworkInfo networkInfo) {

	getGatewayWebService().changeNetworkResponse(networkInfo).execute();
	return new ResultModel();
    }

    @MethodChinaName(cname = "场景模式列表报告", returnStr = "ModeListReport($SenceMode)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/ModeListReport" })
    @ResponseBody
    public ResultModel<Boolean> modeListReport(@RequestBody SenceMode mode) {

	getCommandWebService().modeListReport(mode).execute();
	return new ResultModel();
    }

    @MethodChinaName(cname = "命令执行状态报告", returnStr = "CommandReport($CommandReportStatus)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/CommandReport" })
    @ResponseBody
    public ResultModel<Boolean> commandReport(@RequestBody CommandReportStatus commandReportStatus) {
		logger.info("Method commandReport data:"+JSONObject.toJSONString(commandReportStatus));
	String commandId = commandReportStatus.getCommandId();

	// 心跳拦截
	if (commandId.startsWith("Herat")) {
	    AbstractCometHandle.getCheckHeart().put(commandReportStatus.getCommandId(), System.currentTimeMillis());
	    return new ResultModel();

	} else {

	    getCommandWebService().commandReport(commandReportStatus);
	    return new ResultModel<Boolean>();
	    // return getCommandWebService().commandReport(commandReportStatus);
	}

    }

    @MethodChinaName(cname = "传感器数据报告", returnStr = "DataReport($SensorData)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/DataReport" })
    @ResponseBody
    public ResultModel<Boolean> dataReport(@RequestBody SensorData sensordata) {
		logger.info("Method SensorData data:"+JSONObject.toJSONString(sensordata));

	getDataWebService().addData(sensordata).execute();
	return new ResultModel<Boolean>();
    }

    @MethodChinaName(cname = "查找传感器", returnStr = "FindSensor($SensorListInfo)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/FindSensor" })
    @ResponseBody
    public ResultModel<Boolean> findSensor(@RequestBody SensorListInfo sensorList) {
		logger.info("Method findSensor data:"+JSONObject.toJSONString(sensorList));

	getGatewayWebService().addSensors(sensorList.getSensors()).execute();
	return new ResultModel<Boolean>();
    }

    @MethodChinaName(cname = "网关错误报告", returnStr = "GatewayErrorReport($GatewayErrorReport)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/GatewayErrorReport" })
    @ResponseBody
    public ResultModel<Map<String, List<Command>>> gatewayErrorReport(@RequestBody GatewayErrorReport errorPort) {

	ResultModel<Map<String, List<Command>>> userStatusInfo = new ResultModel<Map<String, List<Command>>>();

	try {


	    List<Command> commandList = getGWAccountWebService().gatewayErrorReport(errorPort).get();
	    userStatusInfo = new ResultModel();
	    Map map = new HashMap();
	    map.put("commandList", commandList);
	    ((ResultModel) userStatusInfo).setData(map);
	} catch (JDSException e) {
	    userStatusInfo = new WebErrorResultModel();
	    ((WebErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
	    ((WebErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
	    logger.error("gatewayErrorReport:出错,GatewayErrorReport1:" + JSON.toJSONString(errorPort), e);

	} catch (ExecutionException e) {
	    logger.error("gatewayErrorReport:出错,GatewayErrorReport2:" + JSON.toJSONString(errorPort), e);
	    userStatusInfo = new WebErrorResultModel();
	    ((WebErrorResultModel) userStatusInfo).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
	    ((WebErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
	}

	return userStatusInfo;

    }

    @MethodChinaName(cname = "网关在线", returnStr = "GatewayOnLine($Gateway)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/GatewayOnLine" })
    @ResponseBody
    public ResultModel<Boolean> gatewayOnLine(@RequestBody Gateway gateway) {

	getGatewayWebService().gatewayOnLine(gateway);
	return new ResultModel();
    }

    @MethodChinaName(cname = "网关下线", returnStr = "GatewayOffLine($Gateway)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/GatewayOffLine" })
    @ResponseBody
    public ResultModel<Boolean> gatewayOffLine(@RequestBody Gateway gateway) {


	getGatewayWebService().gatewayOffLine(gateway);
	return new ResultModel();
    }

    @MethodChinaName(cname = "登录", returnStr = "Login($GWUser)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/Login" })
    @ResponseBody
    public ResultModel<GWUser> login(@RequestBody GWUser userInfo) {
	JDSActionContext.getActionContext().getContext().clear();
		ResultModel<GWUser> userStatusInfo = new ResultModel<GWUser>();
		try {
			GWUser user= getGWAccountWebService().login(userInfo).get();
			userStatusInfo.setData(user);
		} catch (JDSException e) {

			userStatusInfo = new WebErrorResultModel();
			((WebErrorResultModel) userStatusInfo).setErrcode(JDSException.APPLICATIONNOTFOUNDERROR);
			((WebErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
		}

	return userStatusInfo;
    }

    @MethodChinaName(cname = "注销", returnStr = "Logout()")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/Logout" })
    @ResponseBody
    public ResultModel<Boolean> logout() {

	getGWAccountWebService().logout();

	return new ResultModel();
    }

    @MethodChinaName(cname = "传感器下线", returnStr = "SensorOffLine($Sensor)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/SensorOffLine" })
    @ResponseBody
    public ResultModel<Boolean> sensorOffLine(@RequestBody Sensor sensor) {
		logger.info("Method sensorOffLine data:"+JSONObject.toJSONString(sensor));

	getGatewayWebService().sensorOffLine(sensor).execute();
	return new ResultModel();
    }

    @MethodChinaName(cname = "传感器在线", returnStr = "SensorOnLine($Sensor)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/SensorOnLine" })
    @ResponseBody
    public ResultModel<Boolean> sensorOnLine(@RequestBody Sensor sensor) {
		logger.info("Method sensorOnLine data:"+JSONObject.toJSONString(sensor));

	getGatewayWebService().sensorOnLine(sensor).execute();
	return new ResultModel();
    }

    @MethodChinaName(cname = "传感器列表报告", returnStr = "SensorReport($SensorListInfo)")

    @RequestMapping(method = { RequestMethod.POST }, value = { "/SensorReport" })
    @ResponseBody
    public ResultModel<Boolean> sensorReport(@RequestBody SensorListInfo sensorList) {
		logger.info("Method sensorReport data:"+JSONObject.toJSONString(sensorList));

	ResultModel model = new ResultModel();

	getGatewayWebService().syncSensor(sensorList.getSensors());

	return new ResultModel();
    }

    DataWebService getDataWebService() {
	return (DataWebService) EsbFactory.par("$DataWebService");
    }

    CommandWebService getCommandWebService() {
	return (CommandWebService) EsbFactory.par("$CommandWebService");
    }

    GatewayWebService getGatewayWebService() {

	return (GatewayWebService) EsbFactory.par("$GatewayWebService");
    }

    GWAccountWebService getGWAccountWebService() {
	return (GWAccountWebService) EsbFactory.par("$GWAccountWebService");
    }


}
